package other.edan.intlpass.campaign;

import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEvent;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventRequest;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventResponse;
import com.rkhd.platform.sdk.data.model.Campaign;
import com.rkhd.platform.sdk.data.model.NationalArchives__c;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.XObject;
import org.apache.commons.lang.StringUtils;
import other.edan.intlpass.utils.HCDateUtils;
import other.edan.intlpass.utils.HCXObjectService;
import other.edan.intlpass.utils.Result;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 生成市场活动编码
 * @Author: 黎炎松
 * @Date: 2024/8/21 14:21
 */
public class CreateCampaignCode implements RuleEvent {

    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "生成市场活动编码 ==> ";


    /**
     * 执行触发规则事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public RuleEventResponse execute(RuleEventRequest request) throws ScriptBusinessException {
        LOGGER.info(LOGGER_MSG + "触发规则开始处理");
        Long dataId = request.getDataId();
        dealCampaignCode(dataId);

        RuleEventResponse response = new RuleEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }

    public static void main(String[] args) {
        CreateCampaignCode createCampaignCode = new CreateCampaignCode();
        createCampaignCode.dealCampaignCode(3539483803570051L);
        //createCampaignCode.getNewNumber("xxxx2024082111", "20240821");
    }

    /**
     * 处理市场活动编码
     * @param campaignId
     * @return
     */
    public Result dealCampaignCode(Long campaignId) {
        LOGGER.info(LOGGER_MSG + "处理开始 = " + campaignId);
        try {
            // 获取当前国家
            Campaign campaign = new Campaign();
            campaign.setId(campaignId);
            campaign = HCXObjectService.get(campaign);

            // 根据国家档案获取国家代码
            //Integer countryId = campaign.getCountry__c();
            Long nationalId = campaign.getNational__c();
            String sql = "select id,name from nationalArchives__c where id = " + nationalId;
            NationalArchives__c nationalArchives = HCXObjectService.queryOne(sql);
            LOGGER.info(LOGGER_MSG + "nationalArchives: " + nationalArchives);

            // 获取当前国家下最新的一条市场活动,排查当前数据 （不好根据日期直接查询）
            sql = String.format("select id,campaignName,campaignName__c,national__c,createdAt from campaign " +
                    "where id != %s and national__c = %s order by createdAt desc limit 1", campaignId, nationalId);
            List<Campaign> campaignList = HCXObjectService.queryAll(sql);
            LOGGER.info(LOGGER_MSG + "campaignList: " + campaignList);

            // 获取序号 根据日期排序获取最新的序号(序号往前追加，不重置)
            String number = "01";
            String dateStr = HCDateUtils.dateToString(new Date(), "yyyyMMdd");
            if (campaignList != null && campaignList.size() > 0) {
                // xxxx2024082101
                String campaignName= campaignList.get(0).getCampaignName__c();
                number = getNewNumber(campaignName, dateStr);
            }

            // 获取编码  国家代码 + 年月日 + 序号
            String code = "xxxx";
            if (nationalArchives != null) {
                code = nationalArchives.getName();
            }
            String finalCode = code + dateStr + number;
            LOGGER.info(LOGGER_MSG + "finalCode: " + finalCode);

            // 更新编码
            Campaign upCampaign = new Campaign();
            upCampaign.setId(campaignId);
            upCampaign.setCampaignName__c(finalCode);
            OperateResult update = HCXObjectService.update(upCampaign);
            if (!update.getSuccess()) {
                LOGGER.info(LOGGER_MSG + "更新编码异常: " + update.getErrorMessage());
                return Result.error("Update encoding exception: " + update.getErrorMessage());
            }

            LOGGER.info(LOGGER_MSG + "处理成功");
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info(LOGGER_MSG + "处理市场活动编码异常: " + e.getMessage());
            return Result.error("Handle encoding exceptions: " + e.getMessage());
        }
    }

    /**
     * 根据日期以及编码获取最新的序号
     * @param code
     * @return
     */
    public String getNewNumber(String code, String dateStr) {
        String number = "01";
        if (StringUtils.isNotBlank(code)) {
            // todo 序号超过100的情况
            int length = code.length();
            String tempDate = code.substring(length - 10, length - 2);
            String tempNumber = code.substring(length - 2, length);
            System.out.println("tempDate = " + tempDate);
            System.out.println("tempNumber = " + tempNumber);
            // 日期
            if (Objects.equals(tempDate, dateStr)) {
                Integer integer = Integer.valueOf(tempNumber);
                integer++;
                number = integer < 10 ? "0" + integer : integer.toString();
            }
        }
        System.out.println("number = " + number);
        return number;
    }


}
